from datetime import datetime
from django.shortcuts import HttpResponse
from web import models
from web.utils import ipv4_tools
import xlwt
from io import BytesIO


def make_excel(pk_list,):
    now_time = datetime.now().strftime('%Y-%m-%d')
    pk_list = set(pk_list)
    # 设置HTTPResponse的类型
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=%s.xls' % now_time
    # 创建一个文件对象
    wb = xlwt.Workbook(encoding='utf8')
    # 创建一个sheet对象
    sheet = wb.add_sheet('sheet1')

    # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改

    # 写入文件标题
    sheet.write(0, 0, '序号')
    sheet.write(0, 1, '网络地址')
    sheet.write(0, 2, '子网掩码')
    sheet.write(0, 3, '起始地址')
    sheet.write(0, 4, '结束地址')
    sheet.write(0, 5, '网关')
    data_row = 1
    for pk in pk_list:
        subnet_object = models.IpSubnetRecord.objects.filter(id=pk).first()
        subnet = subnet_object.subnet
        network_address = ipv4_tools.get_network_address(subnet)
        net_mask = ipv4_tools.get_net_mask(subnet)
        start_address = ipv4_tools.get_start_addrss(subnet)
        end_address = ipv4_tools.get_end_address(subnet)
        default_gateway = ipv4_tools.get_gateway(subnet)
        # 写入数据
        # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
        # for i in UserTable.objects.all():
        # 格式化datetime
        # pri_time = i.pri_date.strftime('%Y-%m-%d')
        # oper_time = i.operating_time.strftime('%Y-%m-%d')
        sheet.write(data_row, 0, data_row)
        sheet.write(data_row, 1, network_address)
        sheet.write(data_row, 2, net_mask)
        sheet.write(data_row, 3, start_address)
        sheet.write(data_row, 4, end_address)
        sheet.write(data_row, 5, default_gateway)
        data_row = data_row + 1

    # 写出到IO
    output = BytesIO(initial_bytes=None)
    wb.save(output)
    # 重新定位到开始
    output.seek(0)
    response.write(output.getvalue())
    return response